﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.Collections;
using Microsoft.Office.Server.UserProfiles;
using System.Web.Hosting;



namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class QatarID_VisaRenewal_Form : LayoutsPageBase
    {

        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string QatarIDRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string MainLstDetails;

        public static string lstGuid { get; set; }
        public string camlQry { get; set; }
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string refID;
        public static string TaskItemID;
        private static bool Submit = false;

        public static string DocStatus;

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string RequestType = null;

        private int isDuplicateNo;

        public static bool isDuplicateClassName = false;


        string[] buttonVisibilty = new string[5];

        #endregion

        public QatarID_VisaRenewal_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Qatar ID Visa Renewal Forms";
            TaskLstName = "Qatar ID Visa Renewal Tasks";
            CmntsLstName = "Qatar ID Visa Renewal Comments";
            MainLstDetails = "Qatar ID Visa Renewal Details";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                Mode = Request.QueryString["Mode"];
                refID = Request.QueryString["RefID"]; // From Dashboard.
                TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);

                if (Mode == "Edit" || Mode == "View")
                {
                    FormApprovalLoad(); CkGridViewDisplay(); if (Mode == "View") InvisibleButtons();
                }
                else if (Mode == "New")
                {
                    FirstLoadofForm();
                }
                else
                {
                    pnlFullForm.Visible = false;
                    pnlAccessDenied.Visible = true;
                    lblAccessDeniedMsg.Visible = true;
                    lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                }
            }
            if (Mode == "New")
                GetuserDetails();
        }



        /// <summary>
        /// To show and hide Row command button and Footer Row.
        /// In Edit Mode the other user will access the form, that time the command button and add button is not visible.
        /// But the Department of user as Procurement, that time only they can view the command button and add button.
        /// Because the procurement dept user only to enter the Renewal Date in the progress of workflow
        /// </summary>

        private void CkGridViewDisplay()
        {

            string dept = string.Empty;
            dept = GetUserDept();

            gvQatarID.HeaderRow.Cells[7].Visible = false;
            gvQatarID.FooterRow.Cells[7].Visible = false;
            gvQatarID.ShowFooter = false;

            if (Mode == "Edit")
            {
                // To Check user department , whether the renewal date to be shown or not
                if (dept == "Procurement")
                {
                    gvQatarID.HeaderRow.Cells[6].Visible = true;
                    gvQatarID.FooterRow.Cells[6].Visible = true;
                }
                else
                {
                    gvQatarID.HeaderRow.Cells[6].Visible = false;
                    gvQatarID.FooterRow.Cells[6].Visible = false;
                }


                for (int i = 0; i < gvQatarID.Rows.Count; i++)
                {
                    gvQatarID.Rows[i].Cells[1].Enabled = false;

                    if (dept == "Procurement")
                    {
                        gvQatarID.Rows[i].Cells[6].Visible = true;
                        gvQatarID.Rows[i].Cells[7].Visible = false;
                    }
                    else
                    {
                        gvQatarID.Rows[i].Cells[6].Visible = false;
                        gvQatarID.Rows[i].Cells[7].Visible = false;
                    }
                }

            }
            else if (Mode == "View")
            {
                // To check the document status is approved or not, also display the renewal date once the document status gets Approved

                gvQatarID.HeaderRow.Cells[7].Visible = false;
                gvQatarID.FooterRow.Cells[7].Visible = false;

                //gvQatarID.FooterRow.Cells[6].Visible = false;

                if (DocStatus == "Approved")
                {
                    gvQatarID.HeaderRow.Cells[6].Visible = true;

                    for (int i = 0; i < gvQatarID.Rows.Count; i++)
                    {
                        gvQatarID.Rows[i].Cells[1].Enabled = false;
                        gvQatarID.Rows[i].Cells[6].Visible = true;
                        gvQatarID.Rows[i].Cells[6].Enabled = false;

                        gvQatarID.Rows[i].Cells[7].Visible = false;
                    }
                }
                else
                {
                    gvQatarID.HeaderRow.Cells[6].Visible = false;
                    gvQatarID.FooterRow.Cells[6].Visible = false;
                    for (int i = 0; i < gvQatarID.Rows.Count; i++)
                    {
                        gvQatarID.Rows[i].Cells[1].Enabled = false;
                        gvQatarID.Rows[i].Cells[6].Visible = false;
                        gvQatarID.Rows[i].Cells[7].Visible = false;
                    }
                }


            }

        }

        private string GetUserDept()
        {
            string dept = string.Empty;
            UserProfile userProfile = obj.GetUserInfo(SPContext.Current.Web.CurrentUser.LoginName);
            if (userProfile["Department"].Value != null)
                dept = Convert.ToString(userProfile["Department"].Value);
            else
                dept = null;

            return dept;
        }


        /// <summary>
        /// Get User details while enter the user in GridView.
        /// Check the user is exist in Gridview, if exist message will displayed in page, same time user canaot enter the value in corresponding rows.
        /// /// </summary>
        private void GetuserDetails()
        {

            int index = gvQatarID.SelectedIndex;

            if (gvQatarID.Rows.Count > 0)
            {
                PeopleEditor pplUser = (PeopleEditor)gvQatarID.Rows[gvQatarID.Rows.Count - 1].FindControl("pplReqUser");
                Label nationality = (Label)gvQatarID.Rows[gvQatarID.Rows.Count - 1].FindControl("txtNationality");
                Label qatarID = (Label)gvQatarID.Rows[gvQatarID.Rows.Count - 1].FindControl("txtQatarID");
                DateTimeControl expireDt = (DateTimeControl)(gvQatarID.Rows[gvQatarID.Rows.Count - 1].FindControl("dtExpDt"));

                if (CkDuplication() <= 1)
                {
                    isDuplicateClassName = true;

                    if (!string.IsNullOrEmpty(pplUser.CommaSeparatedAccounts))
                    {
                        obj.GetCurrentUserDetails(pplUser.CommaSeparatedAccounts, nationality, qatarID, expireDt);
                    }
                }
                else
                {
                    //nationality.Text = ""; qatarID.Text = ""; expireDt.ClearSelection();
                    //ClientScript.RegisterClientScriptBlock(GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                    //ScriptManager.RegisterClientScriptBlock(this, GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                }


            }

        }

        protected void gvQatarID_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (Mode != "New")
                    e.Row.Cells[6].Visible = true;
                else
                    e.Row.Cells[6].Visible = false;
            }

            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (Mode != "New")
                {
                    e.Row.Cells[6].Visible = true;
                    DateTimeControl renewalDt = (DateTimeControl)e.Row.FindControl("dtRenewDt");
                    renewalDt.OnValueChangeClientScript = "javascript:ckDates()";
                }
                else
                {
                    e.Row.Cells[6].Visible = false;
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Mode != "New")
                    e.Row.Cells[6].Visible = true;
                else
                    e.Row.Cells[6].Visible = false;
            }
        }


        /// <summary>
        /// Grid view row command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvQatarID_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            int id = Convert.ToInt32(e.CommandArgument);
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId = SPContext.Current.Web.ID;
            if (e.CommandName == "ReDelete")
            {
                DataTable dt2 = GetGridViewDataSource();
                dt2.Rows[id].Delete();
                gvQatarID.DataSource = dt2;
                gvQatarID.DataBind();
                SetGridViewValues(dt2);
                if (gvQatarID.Rows.Count == 1)
                {
                    gvQatarID.Rows[0].Cells[7].Enabled = false;
                }
            }
            if (gvQatarID.Rows.Count == 0)
            {
                ViewState["CurrentTable"] = null;
                singlerow();
            }

        }

        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        public void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);

                    if (!string.IsNullOrEmpty(getDocRefNumber[0]) && !string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        singlerow();
                        dtReqDate.SelectedDate = DateTime.Today.Date;
                        if (gvQatarID.Rows.Count == 1)
                        {
                            gvQatarID.Rows[0].Cells[7].Enabled = false;
                        }
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }
                });
            }
            catch (Exception ex)
            {
                //GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::FirstLoadofForm", "Exception in catch block", ex.Message);
            }
        }

        public void singlerow()
        {
            try
            {
                if (ViewState["CurrentTable"] == null)
                {
                    DataTable dt = new DataTable();
                    DataRow dr = null;
                    dt.Columns.Add(new System.Data.DataColumn("NewRow", typeof(string)));
                    dr = dt.NewRow();
                    dr["NewRow"] = "1";
                    dt.Rows.Add(dr);
                    gvQatarID.DataSource = dt;
                    gvQatarID.DataBind();
                    ViewState["CurrentTable"] = dt;
                }
            }
            catch (Exception)
            {

            }
        }


        /// <summary>
        /// add rows for DV expenses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Bbtnadd_Click(object sender, EventArgs e)
        {
            try
            {

                DataTable dt2 = new DataTable();
                dt2 = GetGridViewDataSource();
                DataRow drEmptyRow = dt2.NewRow();
                dt2.Rows.Add(drEmptyRow);
                gvQatarID.DataSource = dt2;
                gvQatarID.DataBind();
                SetGridViewValues(dt2);

                // ClientScript.RegisterClientScriptBlock(GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);

            }
            catch (Exception ex)
            {
                //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::Bbtnadd_Click", "Exception in catch block", ex.Message);
            }

        }

        /// <summary>
        /// To check the gridview contains duplicate users.
        /// And set the control as readonly if duplication occured.
        /// </summary>
        /// <returns></returns>
        private int CkDuplication()
        {
            for (int i = 0; i < gvQatarID.Rows.Count; i++)
            {
                PickerEntity pk = null;
                PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");
                if (user.Entities.Count > 0)
                {
                    pk = (PickerEntity)user.Entities[0];

                    if (isDuplicateNo > 1)
                    {
                        break;
                    }
                    else
                    {
                        isDuplicateNo = 0;
                        for (int j = 0; j < gvQatarID.Rows.Count; j++)
                        {

                            PeopleEditor users = (PeopleEditor)gvQatarID.Rows[j].FindControl("pplReqUser");

                            if (users.Entities.Count > 0)
                            {

                                PickerEntity pkr = (PickerEntity)users.Entities[0];

                                if (!string.IsNullOrEmpty(pkr.DisplayText))
                                {
                                    if (pkr.DisplayText.Contains(pk.DisplayText))
                                        isDuplicateNo++;
                                }
                                if (isDuplicateNo > 1)
                                {
                                    Label nationality = (Label)gvQatarID.Rows[j].FindControl("txtNationality");
                                    Label qatarID = (Label)gvQatarID.Rows[j].FindControl("txtQatarID");
                                    DateTimeControl expireDt = (DateTimeControl)(gvQatarID.Rows[j].FindControl("dtExpDt"));
                                    TextBox remarks = (TextBox)gvQatarID.Rows[j].FindControl("txtRemarks");
                                    nationality.Text = ""; qatarID.Text = ""; expireDt.ClearSelection(); remarks.Text = "";
                                    users.Entities.Clear();
                                    ScriptManager.RegisterClientScriptBlock(this, GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                                    //pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Duplicate records are not allowed!');</script>"));
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return isDuplicateNo;
        }


        /// <summary>
        /// Assign datasource to gridview 
        /// </summary>
        /// <returns></returns>
        private DataTable GetGridViewDataSource()
        {
            DataTable dt2 = new DataTable();
            try
            {
                dt2.Columns.Add("User", typeof(SPFieldUserValue));
                dt2.Columns.Add("Nationality", typeof(string));
                dt2.Columns.Add("QatarID", typeof(string));
                dt2.Columns.Add("QatarExpired", typeof(DateTime));
                dt2.Columns.Add("Remarks", typeof(string));
                dt2.Columns.Add("NewExpiryDate", typeof(DateTime));


                if (gvQatarID.Rows.Count > 0)
                {
                    for (int i = 0; i < gvQatarID.Rows.Count; i++)
                    {
                        PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");
                        DataRow dr1 = dt2.NewRow();

                        if (user.Accounts.Count > 0)
                        {
                            SPContext.Current.Web.EnsureUser(user.CommaSeparatedAccounts);
                            SPUser User = SPContext.Current.Web.SiteUsers[user.CommaSeparatedAccounts];
                            SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, User.ID, User.Name);
                            dr1["User"] = fldUser;
                        }

                        Label nationality = (Label)gvQatarID.Rows[i].FindControl("txtNationality");
                        if (nationality != null)
                            dr1["Nationality"] = Convert.ToString(nationality.Text);
                        Label qatarID = (Label)gvQatarID.Rows[i].FindControl("txtQatarID");
                        if (qatarID != null)
                            dr1["QatarID"] = Convert.ToString(qatarID.Text);

                        DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                        dr1["QatarExpired"] = Convert.ToDateTime(idExp.SelectedDate);

                        TextBox remarks = (TextBox)gvQatarID.Rows[i].FindControl("txtRemarks");
                        if (remarks != null)
                            dr1["Remarks"] = Convert.ToString(remarks.Text);

                        DateTimeControl idRenwal = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtRenewDt");
                        if (idRenwal != null)
                            dr1["NewExpiryDate"] = Convert.ToDateTime(idRenwal.SelectedDate);



                        dt2.Rows.Add(dr1);
                    }

                }
            }
            catch (Exception ex)
            {
                //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::GetGridViewDataSource", "Exception in catch block", ex.Message);
            }
            return dt2;
        }

        /// <summary>
        /// set values to Grid view
        /// </summary>
        /// <param name="dt2"></param>
        private void SetGridViewValues(DataTable dt2)
        {
            DataRow drGetRow;
            SPFieldLookupValue ofldlook = null;
            ArrayList _arrayList;

            decimal rowTotal;

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                drGetRow = dt2.Rows[i];

                PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");

                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["User"])))
                {
                    SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(drGetRow["User"]));
                    PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                    _pickerEntity.Key = fldUser.LookupValue;
                    _pickerEntity.IsResolved = true;
                    _arrayList = new ArrayList();
                    _arrayList.Add(_pickerEntity);
                    user.UpdateEntities(_arrayList);
                }
                Label nationality = (Label)gvQatarID.Rows[i].FindControl("txtNationality");
                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["Nationality"])))
                    nationality.Text = Convert.ToString(drGetRow["Nationality"]);

                Label qatarID = (Label)gvQatarID.Rows[i].FindControl("txtQatarID");
                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["QatarID"])))
                    qatarID.Text = Convert.ToString(drGetRow["QatarID"]);

                if (string.IsNullOrEmpty(Convert.ToString(drGetRow["User"])))
                {
                    DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                    idExp.SelectedDate = Convert.ToDateTime(drGetRow["QatarExpired"]);
                    idExp.ClearSelection();
                }
                else
                {
                    DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                    idExp.SelectedDate = Convert.ToDateTime(drGetRow["QatarExpired"]);
                }
                TextBox remarks = (TextBox)gvQatarID.Rows[i].FindControl("txtRemarks");
                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["Remarks"])))
                    remarks.Text = Convert.ToString(drGetRow["Remarks"]);

                DateTimeControl idRenwal = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtRenewDt");
                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["NewExpiryDate"])))
                    idRenwal.SelectedDate = Convert.ToDateTime(drGetRow["NewExpiryDate"]);

            }


        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (Request.QueryString["Mode"] == "Edit")
                {
                    string formID = null;
                    string refNo = Request.QueryString["RefID"];
                    string taskItemID = Request.QueryString["TaskItemID"];
                    string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                    if (GetSendbackStatus())
                    {
                        if (CheckServersideValidation())
                        {
                            SPLongOperation lop = new SPLongOperation(this.Page);
                            lop.LeadingHTML = "<DIV><H4>Qatar ID Visa Renewal form approval is in progress</H4></DIV>";
                            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                            lop.Begin();
                            obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                                TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, null);
                            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                        }
                    }
                    else
                    {
                        lblError.Text = "Can't be send back. User is not available";
                    }
                }
                else if (Request.QueryString["Mode"] == "New")
                {
                    SaveFormDetails();
                    ClientScript.RegisterClientScriptBlock(GetType(), "Record Saved", "window.close", true);
                }
            }
        }


        /// <summary>
        /// check the user availability
        /// </summary>
        /// <returns></returns>

        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]),
                    lblQIdReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }


        /// <summary>
        /// Save Form details 
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>
        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Qatar ID Visa Renewal form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblQIdReqNo, SiteURL);
                QatarIDRequestNo = Convert.ToString(lblQIdReqNo.Text).Trim();
                if (QatarIDRequestNo.Contains(DateTime.Now.Year.ToString()))
                {
                    lop.Begin();

                    lstGuid = obj.AddQatarID_RequestItems(SiteURL, MainLstName, TaskLstName, CmntsLstName, 0, AttLibName, upfile, WorkflowConfigList, pplcnt,
                        lblQIdReqNo.Text, Convert.ToString(dtReqDate.SelectedDate), CurrentUser.ToLower(), TxtComments.Text);
                    SetQatarIDVisaRenwalDetails();
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
                else
                {
                    lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                }
            });
        }

        /// <summary>
        /// Add gridview items in Qatar ID Visa Renewal Details list
        /// </summary>
        private void SetQatarIDVisaRenwalDetails()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    string referenceNo = lblQIdReqNo.Text;
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList(MainLstDetails);
                            if (oList != null)
                            {
                                for (int i = 0; i < gvQatarID.Rows.Count; i++)
                                {
                                    SPQuery oEmptyQuery = new SPQuery();
                                    oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                                    SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                                    SPListItem oItem = oItemColl.Add();
                                    oItem["Title"] = referenceNo;

                                    PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");
                                    SPUser EnsUser = oWeb.EnsureUser(user.CommaSeparatedAccounts);
                                    if (EnsUser != null)
                                    {
                                        SPUser User = oWeb.EnsureUser(user.CommaSeparatedAccounts); //oWeb.SiteUsers[EnsUser.Name];
                                        SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, User.ID, User.Name);
                                        oItem["Employees"] = fldUser;
                                    }
                                    Label nationality = (Label)gvQatarID.Rows[i].FindControl("txtNationality");
                                    if (nationality != null)
                                        oItem["Nationality"] = Convert.ToString(nationality.Text);
                                    Label qatarID = (Label)gvQatarID.Rows[i].FindControl("txtQatarID");
                                    if (qatarID != null)
                                        oItem["QatarID"] = Convert.ToString(qatarID.Text);

                                    DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                                    oItem["ExpiredDate"] = Convert.ToDateTime(idExp.SelectedDate);

                                    TextBox remarks = (TextBox)gvQatarID.Rows[i].FindControl("txtRemarks");
                                    if (remarks != null)
                                        oItem["Remarks"] = Convert.ToString(remarks.Text);
                                    oWeb.AllowUnsafeUpdates = true;
                                    oItem.Update();
                                    oWeb.AllowUnsafeUpdates = false;
                                }

                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "UpdateQatarIDVisaRenwalDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


        }

        /// <summary>
        /// Set Renewal Date in Qatar ID Visa Renewal Details list while the Procurement user approved the forms
        /// </summary>
        private void UpdateQatarIDVisaRenwalDetails()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    string referenceNo = lblQIdReqNo.Text;
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList(MainLstDetails);
                            if (oList != null)
                            {
                                for (int i = 0; i < gvQatarID.Rows.Count; i++)
                                {
                                    HiddenField hdnID = (HiddenField)gvQatarID.Rows[i].FindControl("itemID");
                                    int id = Convert.ToInt32(hdnID.Value);

                                    SPListItem oItem = oList.GetItemById(id);
                                    DateTimeControl idRenewal = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtRenewDt");
                                    oItem["RenewalDate"] = Convert.ToDateTime(idRenewal.SelectedDate);

                                    gvQatarID.Rows[i].Cells[1].Enabled = false;

                                    HiddenField hdnUser = (HiddenField)gvQatarID.Rows[i].FindControl("hdnUser");

                                    string user = hdnUser.Value;
                                    string[] str = user.Split(';');
                                    SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToInt32(str[0]), str[1]);

                                    SetUserProfiles(fldUser.LookupValue, Convert.ToDateTime(idRenewal.SelectedDate));

                                    oWeb.AllowUnsafeUpdates = true;
                                    oItem.Update();
                                    oWeb.AllowUnsafeUpdates = false;
                                }

                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "UpdateQatarIDVisaRenwalDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        private void SetUserProfiles(string AccountName, DateTime RenewalDate)
        {
            //string currentUser = SPContext.Current.Web.CurrentUser.ToString().Substring(SPContext.Current.Web.CurrentUser.ToString().IndexOf("\\") + 1);

            using (HostingEnvironment.Impersonate())
            {
                string CurrentUser = AccountName;//SPContext.Current.Web.CurrentUser.LoginName;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        using (SPSite oSite = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.SystemAccount.UserToken))
                        {
                            if (RenewalDate.Date >= DateTime.Now)
                            {
                                SPServiceContext context = SPServiceContext.GetContext(oSite);
                                UserProfileManager myProfileManager = new UserProfileManager(context);
                                UserProfile myProfile = myProfileManager.GetUserProfile(CurrentUser);
                                myProfile["QatarIDExpireOn"].Value = RenewalDate.ToShortDateString();
                                myProfile.Commit();

                            }
                            else
                            {
                                //lblMessage.Text = "Date should be greater than or equal to today date";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "SetUserProfiles";
                        obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                    }
                });
            }

        }

        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }
                    ReLoadDetails();
                    //ControlsReadOnly();
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Function to bind data after the Form gets submitted.
        /// </summary>
        /// <param name="SiteURL"></param>

        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
               {

                   using (SPSite osite = new SPSite(SiteURL))
                   {
                       using (SPWeb oweb = osite.OpenWeb())
                       {

                           string RefNo = Convert.ToString(Request.Params["RefID"]);

                           camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + RefNo + "</Value></Eq></Where>";
                           SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                           if (lstDatas != null)
                           {
                               lblQIdReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                               dtReqDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                               DocStatus = Convert.ToString(lstDatas["Document_x0020_Status"]);
                               //Label lblFormID = QatIDComments.FindControl("lblFormID") as Label;
                               //lblFormID.Text = lstDatas.ParentList.ID.ToString();

                               lstGuid = lstDatas.ParentList.ID.ToString();

                               Label lblreferenceNumber = QatIDComments.FindControl("lblReferenceNumber") as Label;
                               Label lblSiteUrl = QatIDComments.FindControl("lblSiteUrl") as Label;
                               Label lblfrmListName = QatIDComments.FindControl("lblfrmListName") as Label;
                               Label lbldocumentypesList = QatIDComments.FindControl("lbldocumentTypes") as Label;
                               Label lblCommentsList = QatIDComments.FindControl("lblCommentsList") as Label;
                               Label lblTaskList = QatIDComments.FindControl("lblTaskList") as Label;

                               lblTaskList.Text = TaskLstName;
                               lblCommentsList.Text = CmntsLstName;
                               lblfrmListName.Text = MainLstName;
                               lbldocumentypesList.Text = DocumentTypesList;
                               lblreferenceNumber.Text = lblQIdReqNo.Text;
                               lblSiteUrl.Text = SiteURL;

                               SPQuery oqry = new SPQuery();
                               oqry.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + RefNo + "</Value></Eq></Where>";

                               ReLoadQatarIDDetails(oweb, lblQIdReqNo.Text, oqry); // Expense List items

                           }
                       }
                   }

               });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Edit the Qatar ID details in the GridView
        /// </summary>
        /// <param name="oweb"></param>
        /// <param name="RefNo"></param>
        /// <param name="oqry"></param>
        /// 
        public void ReLoadQatarIDDetails(SPWeb oweb, string RefNo, SPQuery oqry)
        {
            try
            {
                SPList QatarIDDetails = oweb.Lists.TryGetList(MainLstDetails);
                if (QatarIDDetails != null)
                {
                    SPListItemCollection oItemColl = QatarIDDetails.GetItems(oqry);
                    if (oItemColl.Count > 0)
                    {
                        fnShowGridDetails(oItemColl);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "ReLoadQatarIDDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        private void InvisibleButtons()
        {
            btnCntrls.Visible = false;
            pnlView.Visible = true;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";
        }

        #endregion


        private void GetQatarIDVisaRenwalDetails()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    string referenceNo = lblQIdReqNo.Text;
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList(MainLstDetails);

                            if (oList != null)
                            {
                                for (int i = 0; i < gvQatarID.Rows.Count; i++)
                                {
                                    SPQuery oEmptyQuery = new SPQuery();
                                    oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                                    SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                                    SPListItem oItem = oItemColl.Add();
                                    oItem["Title"] = referenceNo;

                                    PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");
                                    SPUser EnsUser = oWeb.EnsureUser(user.CommaSeparatedAccounts);
                                    if (EnsUser != null)
                                    {
                                        SPUser User = oWeb.EnsureUser(user.CommaSeparatedAccounts); //oWeb.SiteUsers[EnsUser.Name];
                                        SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, User.ID, User.Name);
                                        oItem["Employees"] = fldUser;
                                    }
                                    TextBox nationality = (TextBox)gvQatarID.Rows[i].FindControl("txtNationality");
                                    if (nationality != null)
                                        oItem["Nationality"] = Convert.ToString(nationality.Text);
                                    TextBox qatarID = (TextBox)gvQatarID.Rows[i].FindControl("txtQatarID");
                                    if (qatarID != null)
                                        oItem["QatarID"] = Convert.ToString(qatarID.Text);

                                    DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                                    oItem["ExpiredDate"] = Convert.ToDateTime(idExp.SelectedDate);

                                    TextBox remarks = (TextBox)gvQatarID.Rows[i].FindControl("txtRemarks");
                                    if (remarks != null)
                                        oItem["Remarks"] = Convert.ToString(remarks.Text);
                                    oWeb.AllowUnsafeUpdates = true;
                                    oItem.Update();
                                    oWeb.AllowUnsafeUpdates = false;
                                }

                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "GetQatarIDVisaRenwalDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Qatar ID Visa Renewal form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, submittedfor))
                            UpdateQatarIDVisaRenwalDetails();
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {

                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>Qatar ID Visa Renewal form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();
                    if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                        TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true, 2, submittedfor))
                        UpdateQatarIDVisaRenwalDetails();
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Qatar ID Visa Renewal form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();

                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {
                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, lstGuid, refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, lstGuid, upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, CurrentUser, TxtComments.Text, 0);

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }

        /// <summary>
        /// Edit Qatar ID details in GridView
        /// </summary>
        /// <param name="oitemcollDraw"></param>
        public void fnShowGridDetails(SPListItemCollection oitemcollDraw)
        {
            try
            {
                ArrayList _arrayList;
                DataTable dt = new DataTable();
                DataRow dr = null;
                dt.Columns.Add(new System.Data.DataColumn("sem", typeof(string)));
                dt = (DataTable)ViewState["CurrentTable"];
                if (oitemcollDraw.Count > 0)
                {
                    int count = oitemcollDraw.Count;
                    count -= 1;
                    int inc = 0;
                    if (count == 0)
                    {
                        singlerow();
                    }
                    else
                    {
                        singlerow();
                        dt = (DataTable)ViewState["CurrentTable"];
                        while (inc < count)
                        {
                            dr = dt.NewRow();
                            dt.Rows.InsertAt(dr, 0);
                            gvQatarID.DataSource = dt;
                            gvQatarID.DataBind();
                            inc++;
                        }
                    }
                    for (int i = 0; i < oitemcollDraw.Count; i++)
                    {
                        SPListItem items = oitemcollDraw[i];
                        PeopleEditor user = (PeopleEditor)gvQatarID.Rows[i].FindControl("pplReqUser");

                        SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(items["Employees"]));

                        PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                        _pickerEntity.Key = fldUser.LookupValue;
                        _pickerEntity.IsResolved = true;
                        _arrayList = new ArrayList();
                        _arrayList.Add(_pickerEntity);
                        user.UpdateEntities(_arrayList);

                        HiddenField hdnUser = (HiddenField)gvQatarID.Rows[i].FindControl("hdnUser");
                        hdnUser.Value = fldUser.LookupId + ";" + fldUser.LookupValue;

                        HiddenField hdnID = (HiddenField)gvQatarID.Rows[i].FindControl("itemID");
                        hdnID.Value = Convert.ToString(items["ID"]);

                        Label nationality = (Label)gvQatarID.Rows[i].FindControl("txtNationality");
                        if (!string.IsNullOrEmpty(Convert.ToString(items["Nationality"])))
                            nationality.Text = Convert.ToString(items["Nationality"]);

                        Label qatarID = (Label)gvQatarID.Rows[i].FindControl("txtQatarID");
                        if (!string.IsNullOrEmpty(Convert.ToString(items["QatarID"])))
                            qatarID.Text = Convert.ToString(items["QatarID"]);

                        DateTimeControl idExp = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtExpDt");
                        if (!string.IsNullOrEmpty(Convert.ToString(items["ExpiredDate"])))
                            idExp.SelectedDate = Convert.ToDateTime(items["ExpiredDate"]);

                        TextBox remarks = (TextBox)gvQatarID.Rows[i].FindControl("txtRemarks");
                        remarks.ReadOnly = true;
                        if (!string.IsNullOrEmpty(Convert.ToString(items["Remarks"])))
                            remarks.Text = Convert.ToString(items["Remarks"]);

                        DateTimeControl idRenwal = (DateTimeControl)gvQatarID.Rows[i].FindControl("dtRenewDt");
                        if (!string.IsNullOrEmpty(Convert.ToString(items["RenewalDate"])))
                            idRenwal.SelectedDate = Convert.ToDateTime(items["RenewalDate"]);
                    }

                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal form" + " :: " + "Parent" + " :: " + "Reject";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }
    }
}
